package com.itheima.day2.hiorder;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;

public class C04SimpleStream03<T> {

    private Collection<T> collection;

    private C04SimpleStream03(Collection<T> collection) {
        this.collection = collection;
    }

    public static <T> C04SimpleStream03<T> of(Collection<T> collection) {
        return new C04SimpleStream03<>(collection);
    }

    // C 代表容器类型, supplier 用来创建容器
    public <C> C collect(Supplier<C> supplier, BiConsumer<C, T> consumer) {
        C c = supplier.get(); // 创建了容器
        for (T t : collection) {
            consumer.accept(c, t); // 向容器中添加元素
        }
        return c;
    }

    public <U> C04SimpleStream03<U> map(Function<T, U> function) {
        List<U> result = new ArrayList<>();
        for (T t : collection) {
            U u = function.apply(t);
            result.add(u);
        }
        return new C04SimpleStream03<>(result);
    }

    public static void main(String[] args) {
        List<Integer> list = List.of(1, 2, 3, 4, 5, 1, 2, 3);

        HashSet<Integer> collect1 = C04SimpleStream03.of(list).collect(HashSet::new, HashSet::add);

        StringBuilder collect2 = C04SimpleStream03.of(list).collect(StringBuilder::new, StringBuilder::append);
        StringJoiner collect3 = C04SimpleStream03.of(list).collect(() -> new StringJoiner("-"), (joiner, t) -> joiner.add(t.toString()));
        StringJoiner collect4 = C04SimpleStream03.of(list)
                .map(t -> t.toString())
                .collect(() -> new StringJoiner(","), StringJoiner::add);

        HashMap<Integer, Integer> collect5 = C04SimpleStream03.of(list)
                .collect(HashMap::new, (map, t) -> {
                    if (!map.containsKey(t)) {
                        map.put(t, 1);
                    } else {
                        Integer v = map.get(t);
                        map.put(t, v + 1);
                    }
                });

        HashMap<Integer, AtomicInteger> collect6 = C04SimpleStream03.of(list)
                .collect(HashMap::new, (map, t) -> map.computeIfAbsent(t, k -> new AtomicInteger()).getAndIncrement());

        System.out.println(collect1);
        System.out.println(collect2);
        System.out.println(collect3);
        System.out.println(collect4);
        System.out.println(collect5);
        System.out.println(collect6);
    }

}
